/**
 * Created at 2018/7/12
 * Author: SaintLee
 * <p>
 * Copyright 2018 SaintLee
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.com.saintlee.id;

import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.support.atomic.RedisAtomicLong;
import org.springframework.util.Assert;

import java.util.Date;

/**
 * @Description: <p>ID生成器抽象类</p>
 * @Copyright: <p>Copyright (c) 2018</p>
 * @Company: <p>saintlee.com.cn inc.</p>
 * @date: 2018/7/12 11:44
 * @author: SaintLee
 * @version: v1.0.0
 */
public abstract class AbstractIdGenerator implements IdGenerator {

    protected final RedisAtomicLong counter;


    public AbstractIdGenerator(String seqName, RedisConnectionFactory connectionFactory) {
        Assert.hasText(seqName, "a valid seqName is required");
        Assert.notNull(connectionFactory, "a valid connectionFactory is required");
        this.counter = new RedisAtomicLong(seqName, connectionFactory);
    }

    @Override
    public void set(int value) {
        counter.set(value);
    }

    @Override
    public void set(int value, Date expireTime) {
        counter.set(value);
        counter.expireAt(expireTime);
    }

    @Override
    public Long next() {
        return counter.incrementAndGet();
    }

    @Override
    public Long next(Date expireTime) {
        counter.expireAt(expireTime);
        return counter.incrementAndGet();
    }

    @Override
    public Long next(int increment) {
        return counter.addAndGet(increment);
    }

    @Override
    public Long next(int increment, Date expireTime) {
        counter.expireAt(expireTime);
        return counter.addAndGet(increment);
    }
}
